package com.esisa.listners;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JTextField;



public class CopyPastListner implements MouseListener, ActionListener{
	private String buffer;
	private JTextField J;
	
	public void actionPerformed(ActionEvent e) {
		JMenuItem m = (JMenuItem) e.getSource();
		if(m.getText()=="copier"){
			buffer="";
			if(J.getSelectionStart()!=J.getSelectionEnd())
				buffer=J.getSelectedText();
			else 
				buffer = J.getText();
			
		}
		if(m.getText()=="coller"){
			String h = J.getText();
			StringBuffer chaine = new StringBuffer(h);
			if(J.getSelectionStart()!=J.getSelectionEnd()){
				chaine.delete(J.getSelectionStart(), J.getSelectionEnd());
				chaine.insert(J.getSelectionStart(), buffer);				
			}
			else{
				chaine.insert(J.getCaretPosition(), buffer);
			}
			J.setText(chaine.toString());
		}
		if(m.getText()=="couper"){
			buffer="";
			if(J.getSelectionStart()!=J.getSelectionEnd()){
				String h = J.getText();
				buffer=J.getSelectedText();
				StringBuffer chaine=new StringBuffer(h);
				chaine.delete(J.getSelectionStart(), J.getSelectionEnd());
				J.setText(chaine.toString());
				
			}
			else {
				buffer = J.getText();
				J.setText(null);
			}
			
		}
		
		
	}

	@Override
	public void mouseClicked(MouseEvent e) {
		if(e.getButton()==3){
			this.J = (JTextField) e.getComponent();
			JPopupMenu M = new JPopupMenu();
			JMenuItem m1 = new JMenuItem("couper");
			m1.addActionListener(this);
			JMenuItem m2 = new JMenuItem("copier");
			m2.addActionListener(this);
			JMenuItem m3 = new JMenuItem("coller");
			if(this.buffer == null){
				m3.setEnabled(false);
			}
			else{
				m3.setEnabled(true);
			}
			m3.addActionListener(this);
			M.add(m1);
			M.add(m2);
			M.add(m3);
			M.show(e.getComponent(), e.getX(), e.getY());
			
		}
		
	}

	@Override
	public void mouseEntered(MouseEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mouseExited(MouseEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mousePressed(MouseEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mouseReleased(MouseEvent arg0) {
		// TODO Auto-generated method stub
		
	}

}
